package script

import (
	"autochat-script/script/message"
	"gitee.com/goddesszz/gocommon/myutil"
	"github.com/gorilla/websocket"
	"github.com/samber/lo"
	"log"
	"net/url"
	"time"
)

const (
	Status_Active = 0
	Status_Paused = 1 //暂停回消息
)

// WebSocket服务器地址
var api_url = "ws://localhost:7777/ws"

// 客户端对象
type ChatClient struct {
	UserId string `json:"userId"`

	Status int `json:"status"` //0

	Messages []message.Message `json:"messages"`

	Conn *websocket.Conn `json:"-"`
}

func (c *ChatClient) Connect() bool {
	apiUrl, _ := url.Parse(api_url)
	q := apiUrl.Query()
	q.Set("user", c.UserId)
	q.Set("debug", "")
	apiUrl.RawQuery = q.Encode()

	// 建立WebSocket连接 //?user={{banana}}&debug=
	conn, resp, err := websocket.DefaultDialer.Dial(apiUrl.String(), nil)
	if err != nil {
		log.Fatalf("连接失败: %v", err)
		return false
	}
	log.Printf("握手响应状态码: %d  userId = %s", resp.StatusCode, c.UserId)
	c.Conn = conn

	// 启动一个goroutine持续读取服务器消息
	go func() {
		for {
			// 读取消息类型（文本/二进制）和内容
			msgType, data, err := conn.ReadMessage()
			if err != nil {
				log.Printf("读取消息失败: %v", err)
				return
			}
			// 根据消息类型处理
			switch msgType {
			case websocket.TextMessage:
				//log.Printf("收到文本消息: %s", string(data))

				parse, err := myutil.JsonParse[message.Wrap](string(data))
				if err != nil {
					log.Fatalln("收到文本消息 解析JSON出错 ", err.Error())
				}
				if parse.Message != nil {
					log.Printf("收到聊天消息: %s", parse.Message.Content)

					SaveMessage(c, *parse.Message)
					ResponseChat(c, *parse.Message) //响应消息
				}
			case websocket.BinaryMessage:
				log.Printf("收到二进制消息，长度: %d bytes", len(data))
			}
		}
	}()

	RegisterClient(c) //需要放在connect方法内部吗

	return true
}

func (c *ChatClient) Disconnect() {
	c.Conn.Close() //连接关闭
	log.Println("客户端退出")

	UnRegisterClient(c)
}

// Send 发送消息
func (c *ChatClient) Send(text string, receiver string) {
	if c.UserId == receiver {
		log.Fatalf("发送聊天消息的 sender和receiver 不能为同一个 %v ", receiver)
		return
	}
	log.Printf("发送聊天消息 To %s : %s", receiver, text)

	msgWrap := message.CreateMessage(text, receiver)
	// 发送文本消息
	if err := c.Conn.WriteMessage(websocket.TextMessage, []byte(myutil.JsonToString(msgWrap))); err != nil {
		log.Printf("发送消息失败: %v , err %v", text, err)
		return
	}
	msgWrap.Message.IsSelf = true
	//c.Messages = append(c.Messages, *msgWrap.Message) //存储消息
	SaveMessage(c, *msgWrap.Message)

	time.Sleep(1 * time.Second)
}

func SaveMessage(c *ChatClient, msg message.Message) {
	c.Messages = append(c.Messages, msg) //存储消息

	if len(c.Messages) > 1000 { // 如果超过 1000，删除前 100 个
		c.Messages = lo.Drop(c.Messages, 100)
	}
}
